/**
 * api接口必须传递完整参数集
 * sendTo传递完整的data数据进行验签操作
 */
const axios = require('axios')
const moment = require('moment')

const math = require('mathjs')



const getSleep = require('./timeOut')



class QplwmsInterface {
    constructor(config) {
        this.uri = config.uri
    }
    /**
     * 统一发送
     */
    async sendTo(uri, goData, authorization) {
        let headersData = {
            'Content-Type': 'application/json;charset=utf-8',
            'Authorization': authorization
        }
        let res = ""
        try {
            res = await axios.post(uri, goData, {
                transformRequest: [function (data, headers) {
                    return JSON.stringify(goData)
                }],
                headers: headersData
            })

        } catch (e) {
            res = "9999"
        }

        return res
    }
}



/**
 * querywarehouse
 * 查询仓库列表
 * https://qplwms-api.tuhu.cn/countTask/selectCountTask
 * {"postData":{"locationId":55939,"countTaskResult":"ALL","createStartDateTime":"2001-01-01 00:00:00","createEndDateTime":"2101-01-01 00:00:00"}}
 */
async function querywarehouse(locationId, socket, startTime) {
    let authorization = 'Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6ImhHeXFFYi0tZUFFYTExa2lhZGc4ZXBpSGU0VSIsInR5cCI6IkpXVCIsIng1dCI6ImhHeXFFYi0tZUFFYTExa2lhZGc4ZXBpSGU0VSJ9.eyJuYmYiOjE2MDY3MTEwNjgsImV4cCI6MTYwNjcxNDY2OCwiaXNzIjoiaHR0cHM6Ly9hY2Nlc3MudHVodS5jbiIsImF1ZCI6WyJodHRwczovL2FjY2Vzcy50dWh1LmNuL3Jlc291cmNlcyIsInNpdGVfd21zc29ydGluZ2FwaSJdLCJjbGllbnRfaWQiOiJxcGx3bXMiLCJzdWIiOiIwOGQ4NzZlOTFjN2M0NzkyODRmOTk2MDFhNzc4NGM5YSIsImF1dGhfdGltZSI6MTYwNjcwMzkzMiwiaWRwIjoiV2FyZWhvdXNlRW1wbG95ZWUiLCJpZCI6MTQ1MywiZW1wbG95ZWVfaWQiOiIxNTI5MTk4OTY0NSIsInNjb3BlIjpbIm9wZW5pZCIsInNpdGVfd21zc29ydGluZ2FwaSJdLCJhbXIiOlsiV2FyZWhvdXNlRW1wbG95ZWUiXX0.XLfmxWN5S6C2S1SzYRtivCCHQDwo5wKO5Ra137-YSxacbMAp0FT14vd8kK0L4MD7z2MpmhKWQRyFvHcrUJfu_1vRwm_cr_lElol04DrNDRj3jJOF0Xm_0YftznYRvnCgjhAaWFqOg1hC4iQRH2JkDvrhn9QbNawgn3nxoCE1YO0-gqFa6O1Gynt3EZFSQGD-7E_aSlwBuENeVQfnoglZgKs_VdJemxF1cPApuoaZ9xgNvCdBdCcHp6HGfucpnakg4NDigLQKuz3qybWq-HEFjCQu_-LEcZzmIfeivKccvLwNHCCgVsQZfjh1oXGjUvSbnuVuVOhPMoIwK4RhLFMsig'
    let res = {
        code: '9999', data: {
            count: 0,
            storageNames: []
        }
    }
    const data = { "postData": { "locationId": locationId, "countTaskResult": "ALL", "createStartDateTime": "2001-01-01 00:00:00", "createEndDateTime": "2101-01-01 00:00:00" } }
    let uri = qplwmsInterface.uri + 'countTask/selectCountTask'
    let result = await qplwmsInterface.sendTo(uri, data, authorization)

    if (result.data.code == '10000') {
        if (result.data.data.resultList != 0) {
            let warehouseArys = result.data.data.resultList[0].storageNames
            let pkid = result.data.data.resultList[0].pkid
            for (let i = 0; warehouseArys.length > i; i++) {
                res.data.count = ++res.data.count


                console.log(`${res.data.count}、开始执行：${warehouseArys[i]}`)
                socket.emit('outputmsg', `${res.data.count}、开始执行：${warehouseArys[i]}`)


                let articles = await queryitem(pkid, warehouseArys[i], socket, authorization)
                let warehousearticles = {
                    warehouse: warehouseArys[i],
                    articles: articles
                }
                res.data.storageNames.push(warehousearticles)
                res.code = '0000'

            }
        } else {
            socket.emit('outputmsg', `发现${result.data.data.resultList.length}个库位；赶紧在开个！`)
            console.log(`发现${result.data.data.resultList.length}个库位；赶紧在开个！`)
        }
    }
    if (res.code == '0000') {
        socket.emit('outputmsg', `执行完毕：共 ${res.data.count} 个库位；`)
        socket.emit('outputmsg', `响应消息：${JSON.stringify(res.data.storageNames)}`)
        console.log(`执行完毕：共 ${res.data.count} 个库位；`)
    }
    let endDate = moment()
    let endTime = endDate.valueOf()

    socket.emit('outputmsg', `结束时间：${endDate.format('YYYY-MM-DD HH:mm:ss')}`)
    socket.emit('outputmsg', `耗&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp时：${endTime - startTime}ms`)
    // index.ejs 判断使用
    socket.emit('outputmsg', res.code)

    console.log(`结束时间：${endDate.format('YYYY-MM-DD HH:mm:ss')}`)
    console.log(`耗时：${endTime - startTime}ms`)
    return res
}

/**
 * queryitem
 * 查询库位物品
 * https://qplwms-api.tuhu.cn/countTask/selectCountTaskByTaskId
 * {"postData":{"storageName":"7S-A04-13","taskId":192369,"isMappingSysNum":true}}
 */
async function queryitem(taskId, storageName, socket, authorization) {
    let unknownAry = []
    const data = { "postData": { "storageName": storageName, "taskId": taskId, "isMappingSysNum": true } }
    let uri = qplwmsInterface.uri + 'countTask/selectCountTaskByTaskId'
    let result = await qplwmsInterface.sendTo(uri, data, authorization)
    if (result.data.code == '10000') {
        let itemArys = result.data.data.countTaskProducts

        for (let i = 0; itemArys.length > i; i++) {
            let obj = itemArys[i]
            if (obj.countStatus == '') {
                // 执行库位中的物品
                await getSleep(3000, 5000)
                let resitem = await additem(taskId, obj, authorization)
                if (resitem.data.code == '10000') {
                    socket.emit('outputmsg', `&nbsp&nbsp&nbsp&nbsp[y] 当前[${storageName}]库位：[${obj.pid}] - 盘库成功；数量：[${obj.systemNum}]；`)
                    console.log(`\t[y] 当前[${storageName}]库位：[${obj.pid}]。盘库成功；数量：[${obj.systemNum}]；`)
                    unknownAry.push('成功 - [' + obj.pid + '] - 数量 - [' + obj.systemNum + ']')
                } else {
                    socket.emit('outputmsg', `&nbsp&nbsp&nbsp&nbsp[x] 当前[${storageName}]库位：[${obj.pid}] - 盘库失败；数量：[${obj.systemNum}]；`)
                    console.log(`   [x] 当前[${storageName}]库位：[${obj.pid}]。盘库失败；数量：[${obj.systemNum}]；`)
                    unknownAry.push('失败 - [' + obj.pid + '] - 数量 - [' + obj.systemNum + ']')
                }
            } else {
                socket.emit('outputmsg', `&nbsp&nbsp&nbsp&nbsp[o] 当前[${storageName}]库位：[${obj.pid}]已盘；数量：[${obj.systemNum}]；状态：[${obj.countStatus}]；`)
                console.log(`\t[o] 当前[${storageName}]库位：[${obj.pid}]已盘；数量：[${obj.systemNum}]；状态：[${obj.countStatus}]；`)
                unknownAry.push('已盘 - [' + obj.pid + '] - 数量 - [' + obj.systemNum + '] - 状态 - [' + obj.countStatus + ']')
            }
        }
    }
    return unknownAry
}

/**
 * 物品提交
 * https://qplwms-api.tuhu.cn/countTask/createQPLCountedProduct
    appId: ""
    appName: ""
    appVersion: ""
    countedNum: 1
    createdBy: "15291989645"
    locationId: 55939
    pid: "WP-LKK-HYSWG|25"
    requestTime: ""
    storage: "11S-A04-05"
    systemNum: 1
    taskId: 192369
    taskProductId: 49388174
 */
async function additem(taskId, item, authorization) {
    const data = {
        postData: {
            appId: "",
            appName: "",
            appVersion: "",
            countedNum: item.systemNum,
            createdBy: item.taskOwner == '' || item.taskOwner == null ? '15291989645' : item.taskOwner,
            locationId: 55939,
            pid: item.pid,
            requestTime: "",
            storage: item.storageName,
            systemNum: item.systemNum,
            taskId: taskId,
            taskProductId: item.countProductId,
        }
    }
    // let resitem = { data: { code: '9999' } }
    // return resitem
    let uri = qplwmsInterface.uri + 'countTask/createQPLCountedProduct'
    return await qplwmsInterface.sendTo(uri, data, authorization)
}

// 地址
let qplwmsUrl = 'https://qplwms-api.tuhu.cn/'
let qplwmsInterface = new QplwmsInterface({
    uri: qplwmsUrl
})



/**
 * querywarehouse
 * 查询仓库列表
 * https://qpl-tms-api.tuhu.cn/front/deliveryOrder/queryDeliveryOrderByPage
 */
async function queryDeliveryOrderByPage(res, data, authorization) {
    res.code = '9999'
    let result = ''
    if (authorization == "") {
        authorization = 'Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6ImhHeXFFYi0tZUFFYTExa2lhZGc4ZXBpSGU0VSIsInR5cCI6IkpXVCIsIng1dCI6ImhHeXFFYi0tZUFFYTExa2lhZGc4ZXBpSGU0VSJ9.eyJuYmYiOjE2MTI3NjE0NzYsImV4cCI6MTYxMjc2NTA3NiwiaXNzIjoiaHR0cHM6Ly9hY2Nlc3MudHVodS5jbiIsImF1ZCI6WyJodHRwczovL2FjY2Vzcy50dWh1LmNuL3Jlc291cmNlcyIsInlld3VhcGkiXSwiY2xpZW50X2lkIjoicXBsLXRtcyIsInN1YiI6IjA4ZDdmYzY0Y2MzNTQ5ZWE4MjU4MTQyZWE5N2I1MjAxIiwiYXV0aF90aW1lIjoxNjEyNzYxNDc2LCJpZHAiOiJFbXBsb3llZSIsIm5hbWUiOiLlvKDmtbflhpvvvIjonIDov5Dovr7vvIkiLCJlbWFpbCI6InpoYW5naGFpanVuX3N5ZEB0dWh1LmNuIiwicGhvbmVfbnVtYmVyIjoiMTUyOTE5ODk2NDUiLCJlbXBsb3llZV9pZCI6Ijk4MTAwMyIsInNjb3BlIjpbIm9wZW5pZCIsInlld3VhcGkiXSwiYW1yIjpbIkVtcGxveWVlIl19.QkTFNP1dvvvmyaSwzM4DeYGiYGXMnqowjajBQ1Z3YRaZjIkTwWVYCkTjLXYzwhcGjkIUGdsGoOli7_d7TcCq6s5Bfna7Qm_lfWoxQB6Fo9S-tc3XB7k-09MfGJmHo8QI34wAda8yv-Vtmjn7k5190cu3C4owErvM_ZWjWRyzZdWyJ6yR4-CuizgmGvgs_D0vZbUnQWyoH1izE53yPpgV4Ymwwio9rwDodLpSOF4jeQ1x-HCtmtIccdV8fLkVUV32P3hA02sjROmMCWazhydRx2Gs97Pc9Y6_yQx7-7CG9u3KWfBg1Tgi1edR-fAxMsUduU3uq_Ag92n3rwvmZvwb9A'
    }
    let url = 'https://qpl-tms-api.tuhu.cn/front/deliveryOrder/queryDeliveryOrderByPage'

    result = await qplwmsInterface.sendTo(url, data, authorization)

    if (result.status == 200) {
        if (result.data.code == '10000') {
            let deliveryOrders = result.data.data.deliveryOrders

            if (result.data.data.count==0){
                res.code = '9999'
                res.info = `当前${data.postData.createTimeStart} - ${data.postData.createTimeEnd}时间段，未查询到配送信息！`
                return res
            }else{
                res = {
                    code: '0000',
                    data: {
                        deliveryOrders: deliveryOrders
                    },
                    info: '以获取数据，准备分组计算'
                }

                if (deliveryOrders.length >= 0) {
                    for (let i = 0; deliveryOrders.length > i; i++) {
                        let obj = deliveryOrders[i]
                        for (let key in obj) {
                            if ('idealFee' == key) {
                                if (obj[key] != null) {
                                    res.data.countFee = math.evaluate(`${res.data.countFee == null ? 0 : res.data.countFee}+${obj[key]}`)
                                }
                            }
                        }
                    }
                    // res.data.deliveryGroup = sortClass(deliveryOrders)
                    res.data.deliveryGroupCountFee = groupByName(deliveryOrders)
                }
                res.info = `计算完成`
            }
        }
    } else {
        res.info = `401 - 请更换Authorization - 授权码`
    }
    return res
}



/**
 * 分组统计数据
 * @param {} groupData 
 */
function groupByName(groupData) {

    let result = groupData.reduce((prevValue, currentValue) => {


        let index = -1;
        prevValue.some((item, i) => {
            if (item.driverName == currentValue.driverName) {
                index = i;
                return true;
            }
        })
        if (index > -1) {

            if (currentValue.idealFee != null) {
                prevValue[index].idealFee = math.evaluate(`${prevValue[index].idealFee}+${currentValue.idealFee}`)
            }
            prevValue[index].driverNumber = math.evaluate(`${prevValue[index].driverNumber}+1`)

            prevValue[index].driverOutNumber = math.evaluate(`${prevValue[index].driverOutNumber}+${currentValue.orderType == "asOrder" ? 1 : 0}`)
            prevValue[index].driverLoseNumber = math.evaluate(`${prevValue[index].driverLoseNumber}+${currentValue.orderState == 99 ? 1 : 0}`)

        } else {
            prevValue.push({
                driverName: currentValue.driverName,
                driverPhone: currentValue.driverPhone,
                driverNumber: 1,  // 总单数
                driverOutNumber: currentValue.orderType == "asOrder" ? 1 : 0, //  退货单- 已完成
                driverLoseNumber: currentValue.orderState == 99 ? 1 : 0, // 已取消
                idealFee: 0 // 总金额
            })
        }
        return prevValue;
    }, []);
    return result;
}














module.exports = { querywarehouse, queryDeliveryOrderByPage }

